package com.itheima.service.impl;

import com.itheima.anno.LogOperation;
import com.itheima.domain.pojo.Dept;
import com.itheima.exception.CustomerException;
import com.itheima.exception.DeleteClazzException;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author:篍
 * @Date: 2025/07/10 10:40
 * @Description:Fighting TODO
 */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;


    /**
     *
     * @return 逻辑处理部门集合的结果
     */
    @Override
    public List<Dept> findAll() {
        return deptMapper.findAll();
    }

    @Override
    public Integer deleteDeptById(Integer id) {
        long count=empMapper.countEmpByDeptId(id);
        if(count>0){
            throw new DeleteClazzException("对不起");
        }
        return deptMapper.deleteDeptById(id);
    }

    /**
     * 添加部门
     * @param部门
     * @return修改行数
     */
    @Override
    public Integer addDept(Dept dept) {
        Set<String> deptName = findAll().stream().map(Dept::getName).collect(Collectors.toSet());
        if (deptName.contains(dept.getName())) {
            throw new CustomerException(dept.getName()+"已存在，请修改");
        }
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        return deptMapper.addDept(dept);
    }

    @Override
    public Dept findOneDeptById(Integer deptId) {
        return deptMapper.findOneDeptById(deptId);
    }

    @Override
    public void updateDept(Dept dept) {
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
